package com.lishui.waterfriend.aspect;

import com.lishui.waterfriend.annotation.JudgeEmpty;
import com.lishui.waterfriend.contant.MessageConstant;
import com.lishui.waterfriend.enums.OperationTypeEnum;
import com.lishui.waterfriend.exception.ParameterException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 判空切面
 */
@Aspect
@Component
@Slf4j
@Order(3)
public class AutoJudgeEmptyAspect {
    @Pointcut("execution(* com.lishui.waterfriend.controller.*.*(..)) && @annotation(com.lishui.waterfriend.annotation.JudgeEmpty)")
    public void autoJudgeEmptyPointcut() {
    }

    @Before("autoJudgeEmptyPointcut()")
    public void autoJudgeEmptyAdvice(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        JudgeEmpty judgeEmpty = signature.getMethod().getAnnotation(JudgeEmpty.class);
        // 判空
        Object[] args = joinPoint.getArgs();
        if (OperationTypeEnum.YES.equals(judgeEmpty.value())) {
            if (args == null || args.length == 0) throw new ParameterException(MessageConstant.EMPTY_PARAMETER);
            Object entity = args[0];
            if (entity == null) throw new ParameterException(MessageConstant.EMPTY_PARAMETER);
        }
    }
}
